<template>
  <el-dialog
    top="30px"
    width="90%"
    class="dialog-sm"
    custom-class="max-w"
    style="--max-width: 1200px"
    append-to-body
    title="缴费登记"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <detail-view :related-id="editRow.customer_related_id"></detail-view>
    <hr />

    <div class="d-flex align-items-center justify-content-between mb-2">
      <div class="text-muted" style="font-size: 1.2rem"></div>
      <div class="text-right">
        <el-button
          @click="getRegister()"
          size="small"
          icon="el-icon-refresh"
          :loading="loading"
        ></el-button>
        <el-button
          type="primary"
          size="small"
          v-if="!isViewMode && isAbUser"
          :disabled="loading"
          @click="handleEdit()"
        >
          添加登记
        </el-button>
      </div>
    </div>

    <div class="row text-body mb-2">
      <div class="col">本期应缴时间：{{ editRow.dueWarrantDate }}</div>
      <div class="col text-center">本期应缴金额：{{ editRow.due_warrant_fee || '-' }}万元</div>
      <div class="col text-right">
        实缴合计：{{ finishedTotalFunds || '-' }}{{ totalFundsUnit }}
      </div>
    </div>

    <table
      class="table table-sm table-bordered vertical-align-middle text-center"
      v-loading="loading"
    >
      <thead>
        <tr>
          <td>登记人员</td>
          <td>登记时间</td>
          <td>登记金额(万元)</td>
          <td>到账时间</td>
          <td>到账金额(万元)</td>
          <td>缴费状态</td>
          <td>备注</td>
          <td>操作</td>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in tableData" :key="item.id || index">
          <td>{{ item.submit_person_name }}</td>
          <td>{{ item.actual_warrant_date || '-' }}</td>
          <td>{{ item.actual_warrant_fee || '-' }}</td>
          <td>{{ item.confirm_fee_time || '-' }}</td>
          <td>{{ item.confirm_warrant_fee || '-' }}</td>
          <td :class="`text-${item.payStatusStyle}`">{{ item.payStatusLabel }}</td>
          <td>{{ item.remark }}</td>
          <td>
            <template v-if="!isViewMode">
              <el-button
                v-if="item.payStatus === PayStatus.ToSubmit && !hasOrderFinished && isAbUser"
                @click="handleEdit(item)"
                size="small"
                icon="el-icon-edit"
              ></el-button>
              <el-button
                v-if="item.payStatus === PayStatus.ToSubmit && isAbUser"
                @click="handleDelete(item)"
                size="small"
                icon="el-icon-delete"
              ></el-button>
              <el-button
                v-if="item.payStatus === PayStatus.ToApply && isFinanceUser"
                @click="handleApply(item)"
                size="small"
              >
                <i class="fa fa-gavel"></i>
              </el-button>
            </template>
            <el-button size="small" icon="el-icon-search" @click="handleView(item)"></el-button>
          </td>
        </tr>
        <tr v-if="!loading && !tableData.length">
          <td colspan="7">
            <div class="text-center text-muted p-2">暂无登记数据</div>
          </td>
        </tr>
        <tr v-if="tableData.length" class="font-weight-bold">
          <td colspan="4">缴费合计</td>
          <td>{{ finishedTotalFunds }}{{ totalFundsUnit }}</td>
          <td colspan="3"></td>
        </tr>
      </tbody>
    </table>

    <div class="text-center my-3" v-if="!isViewMode">
      <el-button
        type="primary"
        plain
        v-if="isAbUser"
        :disabled="loading"
        :loading="submitLoading"
        @click="handleSubmitApply"
      >
        提交审核
      </el-button>
      <el-button @click="beforeClose" :disabled="submitLoading">取消</el-button>
    </div>

    <register-edit-dialog
      :visible.sync="editVisible"
      :edit-row="editRegisterRow"
      :collect-row="editRow"
      @success="handleSuccess()"
    ></register-edit-dialog>

    <register-view-dialog :visible.sync="viewVisible" :register-id="viewId"></register-view-dialog>

    <register-apply-dialog
      :visible.sync="applyVisible"
      :edit-row="applyRow"
      :collect-row="editRow"
      @success="handleSuccess()"
    ></register-apply-dialog>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  enumPayStatus,
  enumPayStatusStyle,
  PayStatus,
} from '@/bigcredit/views/settle/collect/model'
import { formatToDay } from '@/common/plugins/tools/date'
import { num } from '@/common/plugins/tools/format'
import { strip } from '@vimi/utils-tool'

import DetailView from '@/bigcredit/views/settle/collect/components/DetailView.vue'
import RegisterEditDialog from '@/bigcredit/views/settle/collect/RegisterEditDialog'
import RegisterViewDialog from '@/bigcredit/views/settle/collect/RegisterViewDialog'
import RegisterApplyDialog from '@/bigcredit/views/settle/collect/RegisterApplyDialog'

export default {
  components: {
    DetailView,
    RegisterEditDialog,
    RegisterViewDialog,
    RegisterApplyDialog,
  },
  props: {
    visible: Boolean,
    editRow: {
      type: Object,
      default() {
        return {}
      },
    },
    viewMode: {
      type: Number,
      default: 0, // 0 编辑，1 查看所有登记，2 只查看已审核的登记
    },
  },
  data() {
    return {
      PayStatus,
      loading: false,
      tableData: [],

      // 编辑
      editRegisterRow: {},
      editVisible: false,

      // 提交审核
      submitLoading: false,

      // 查看
      viewVisible: false,
      viewId: '',

      // 账务人员审核
      applyVisible: false,
      applyRow: {},
    }
  },
  computed: {
    ...mapGetters(['user', 'userId']),
    isAbUser() {
      return [this.editRow.res_a, this.editRow.res_b].includes(this.userId)
    },
    isFinanceUser() {
      return this.user.scopeArr.includes('financeO')
    },
    hasOrderFinished() {
      return +this.editRow.pay_status === PayStatus.Finished
    },
    isViewMode() {
      return this.viewMode !== 0 || this.hasOrderFinished
    },

    // 本期合计
    finishedTotalFunds() {
      const total = this.tableData.reduce((p, c) => {
        if (c.payStatus === PayStatus.Finished) {
          p += num(c.confirm_warrant_fee)
        }
        return p
      }, 0)
      return strip(total)
    },
    totalFundsUnit() {
      return this.finishedTotalFunds ? '万元' : ''
    },

    // 累计登记金额
    // registerTotalFunds() {
    //   const total = this.totalData.reduce((p, c) => {
    //     p += num(c.actual_warrant_fee)
    //     return p
    //   }, 0)
    //   return strip(total)
    // },
    // 累计核算（应收）
    // accountingFunds() {
    //   return num(this.editRow.check_warranty_fee)
    // },
    // 累计缴费（实收）
    // payedFunds() {
    //   return num(this.editRow.payed_warranty_fee)
    // },
    // 可登记的金额
    // registerLeftFunds() {
    //   return Math.max(sub(this.accountingFunds, this.registerTotalFunds), 0)
    // },
    // 可审批的金额
    // applyLeftFunds() {
    //   return Math.max(sub(this.accountingFunds, this.finishedTotalFunds), 0)
    // },
  },
  watch: {
    visible: {
      handler: function (val) {
        val && this.getRegister()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },
    async getRegister() {
      // 收取列表id
      const collectId = this.editRow.id
      if (!collectId) return

      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData({
          table: 'credit_warrant_fee_register',
          params: {
            'related_id.eq': collectId,
            'pay_status.eq': this.viewMode === 2 ? '2' : '',
          },
          order: {
            actual_warrant_date: 'asc',
          },
        })
      )
      this.loading = false

      this.tableData = ((res && res.data) || []).map(this.dataAdapter)
    },
    dataAdapter(row) {
      row.actual_warrant_date = formatToDay(row.actual_warrant_date)
      row.confirm_fee_time = formatToDay(row.confirm_fee_time)
      row.payStatus = +(row.pay_status || 0)
      row.payStatusLabel = enumPayStatus[row.payStatus] || ''
      row.payStatusStyle = enumPayStatusStyle[row.payStatus] || ''
      return row
    },
    handleEdit(row = {}) {
      this.editRegisterRow = row
      this.editVisible = true
    },
    // 删除
    handleDelete(row) {
      this.$utils
        .msgbox({
          message: '确定删除此登记信息?',
          beforeClose: () =>
            this.$api.deleteData({
              table: 'credit_warrant_fee_register',
              id: row.id,
            }),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.handleSuccess()
        })
        .catch(err => {
          this.$message.error('删除失败，请重试！')
          throw new Error(err)
        })
    },
    // 提交审核
    handleSubmitApply() {
      const applyData = this.tableData.filter(r => r.payStatus === PayStatus.ToSubmit)
      if (!applyData.length) {
        return this.$message.warning('没有需要提交审核的登记信息')
      }

      const data = applyData.map(r => ({
        id: r.id,
        pay_status: 1,
      }))
      this.$utils
        .msgbox({
          message: `确定提交这 ${data.length} 条登记信息?`,
          beforeClose: () => this.submitApply(data),
        })
        .then(() => {
          this.$message.success('提交审核成功！')
          this.handleSuccess()
        })
        .catch(err => {
          this.$message.error('提交审核失败，请重试！')
          throw new Error(err)
        })
    },
    submitApply(data) {
      this.submitLoading = true
      return this.$api
        .updateBatch({
          table: 'credit_warrant_fee_register',
          data,
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    // 账务人员审核
    handleApply(row = {}) {
      this.applyRow = row
      this.applyVisible = true
    },
    // 查看
    handleView(row) {
      this.viewVisible = true
      this.viewId = row.id
    },
    handleSuccess() {
      this.$emit('success')
      this.getRegister()
    },
  },
}
</script>
<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
</style>
